//
//  NSString+IgnoreEmojiString.m
//  Emoji
//
//  Created by huchu on 2018/6/28.
//  Copyright © 2018年 sysjones. All rights reserved.
//

#import "NSString+IgnoreEmojiString.h"
#import "NSString+EMOEmoji.h"
@implementation NSString (IgnoreEmojiString)
-(NSString*)substringIgnoreEmojiToIndex:(NSInteger)index
{
    NSArray *emojiRangesArray = [self emo_emojiRanges];
    NSInteger stringLength=self.length;
    NSInteger allemojiCount=0;
    NSInteger purestringLength=0;
    NSInteger toIndex=0;
    NSInteger i=0;
    NSInteger lastEmojiLocation=0;
    for (i = 0; i < emojiRangesArray.count; i++) {
        NSValue*value= [emojiRangesArray objectAtIndex:i];
        NSRange range= [value rangeValue];
        purestringLength = range.location-allemojiCount;
        allemojiCount += range.length;
        //NSLog(@"allemojiCount=%d,  purestringLength= %d",allemojiCount, purestringLength );
        if (purestringLength>=index) {
            toIndex=range.location-(purestringLength-index);
            if (purestringLength>index) {
                break;
            }
        }
        lastEmojiLocation=range.location+range.length;
    }
    if(purestringLength<=index){
        toIndex=lastEmojiLocation+(index-purestringLength);
    }
    toIndex = MIN(stringLength,  MAX(toIndex, index));
    return [self substringToIndex:toIndex];
}

-(NSInteger)emojiLength{
    __block NSInteger  alllength=0;
    [self.emo_emojiRanges enumerateObjectsUsingBlock:^(NSValue*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        alllength+= [obj rangeValue].length;
    }];
    return alllength;
}



@end
